import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userAPI } from '@/api/userAPI'

export const useAuthStore = defineStore('auth', () => {
    const user = ref(null)
    const isLoading = ref(false)
    const error = ref(null)

    // 初始化认证状态
    const initializeAuth = () => {
        const savedUser = userAPI.getCurrentUser()
        console.log('🔍 初始化认证状态 - 从本地存储获取用户:', savedUser)

        if (savedUser) {
            if (!userAPI.isLoginExpired(savedUser)) {
                user.value = savedUser // 包含id字段
                console.log('✅ 恢复登录状态（有效）:', user.value)
            } else {
                console.log('🔐 登录状态已过期，清理数据')
                user.value = null
                userAPI.logout()
            }
        } else {
            console.log('ℹ️ 本地存储无有效用户信息')
            user.value = null
        }
    }

    // 登录方法（同步包含id的用户信息）
    const login = async (phone, password) => {
        isLoading.value = true
        error.value = null

        try {
            console.log('🔑 开始登录:', { phone, passwordLength: password?.length || 0 })

            const result = await userAPI.login({ phone, password })
            console.log('📨 登录结果:', result)

            if (result.success && result.data) {
                user.value = result.data // 包含id、phone、role等
                localStorage.setItem('user', JSON.stringify(result.data))
                console.log('✅ 登录成功 - 状态同步完成:', {
                    memoryUser: user.value,
                    localStorageUser: JSON.parse(localStorage.getItem('user'))
                })

                return {
                    success: true,
                    message: result.message,
                    data: user.value
                }
            } else {
                error.value = result.message || '登录失败'
                console.log('❌ 登录失败:', error.value)
                return {
                    success: false,
                    message: error.value
                }
            }
        } catch (err) {
            console.error('💥 登录异常:', err)
            error.value = '网络错误，请稍后重试'
            return {
                success: false,
                message: error.value
            }
        } finally {
            isLoading.value = false
        }
    }

    // 从后端刷新用户信息（保留id）
    const refreshUserFromBackend = async () => {
        isLoading.value = true
        error.value = null

        try {
            console.log('🔄 从后端刷新用户信息')
            const currentUser = userAPI.getCurrentUser();
            if (!currentUser?.phone) {
                return { success: false, message: '未登录，无法刷新用户信息' };
            }

            let result;
            if (userAPI.hasRole('ROLE_ADMIN')) {
                const listResult = await userAPI.getUsersList()
                if (listResult.success && Array.isArray(listResult.data)) {
                    const userInfo = listResult.data.find(u => u.phone === currentUser.phone)
                    result = userInfo ? {
                        success: true,
                        data: {
                            id: userInfo.id || currentUser.id, // 确保id存在
                            phone: userInfo.phone,
                            role: userInfo.role,
                            status: userInfo.status
                        },
                        message: '刷新用户信息成功'
                    } : {
                        success: false,
                        message: '未找到当前用户信息'
                    }
                } else {
                    result = { success: false, message: '获取用户列表失败' }
                }
            } else {
                result = {
                    success: true,
                    data: currentUser,
                    message: '普通用户无需刷新'
                }
            }

            if (result.success && result.data) {
                const mergedData = {
                    ...result.data,
                    loginTime: user.value?.loginTime || result.data.loginTime,
                    rawLoginTime: user.value?.rawLoginTime || result.data.rawLoginTime
                }
                user.value = mergedData
                localStorage.setItem('user', JSON.stringify(mergedData))
                console.log('✅ 刷新成功 - 状态同步完成:', user.value)

                return {
                    success: true,
                    message: result.message,
                    data: user.value
                }
            } else {
                const errMsg = result.message || '刷新用户信息失败'
                console.log('❌ 刷新失败:', errMsg)
                return {
                    success: false,
                    message: errMsg
                }
            }
        } catch (err) {
            console.error('💥 刷新异常:', err)
            error.value = '网络错误，请稍后重试'
            return {
                success: false,
                message: error.value
            }
        } finally {
            isLoading.value = false
        }
    }

    // 注销账户
    const deleteUser = async (phone) => {
        isLoading.value = true
        error.value = null

        try {
            console.log('🗑️ 注销账户:', phone)
            const result = await userAPI.deleteUser(phone)
            console.log('📨 注销响应:', result)

            if (result.success) {
                user.value = null
                userAPI.logout()
                console.log('✅ 账户注销成功（状态已清理）')
                return {
                    success: true,
                    message: result.message
                }
            } else {
                error.value = result.message || '注销失败'
                console.log('❌ 注销失败:', error.value)
                return {
                    success: false,
                    message: error.value
                }
            }
        } catch (err) {
            console.error('💥 注销异常:', err)
            error.value = '网络错误，请稍后重试'
            return {
                success: false,
                message: error.value
            }
        } finally {
            isLoading.value = false
        }
    }

    // 注册方法
    const register = async (userData) => {
        isLoading.value = true
        error.value = null

        try {
            console.log('📝 开始注册:', userData)
            const result = await userAPI.register(userData)
            console.log('📨 注册结果:', result)

            if (result.success && result.data) {
                user.value = result.data // 包含id
                localStorage.setItem('user', JSON.stringify(result.data))
                console.log('✅ 注册成功（状态已同步）')
                return {
                    success: true,
                    message: result.message,
                    data: result.data
                }
            } else {
                error.value = result.message || '注册失败'
                console.log('❌ 注册失败:', error.value)
                return {
                    success: false,
                    message: error.value
                }
            }
        } catch (err) {
            console.error('💥 注册异常:', err)
            error.value = '网络错误，请稍后重试'
            return {
                success: false,
                message: error.value
            }
        } finally {
            isLoading.value = false
        }
    }

    // 修改密码
    const changePassword = async (phone, newPassword) => {
        isLoading.value = true
        error.value = null

        try {
            console.log('🔐 修改密码:', phone)
            const result = await userAPI.alterPassword(phone, newPassword)
            console.log('📨 修改密码结果:', result)

            if (result.success) {
                console.log('✅ 密码修改成功')
                this.logout()
                return {
                    success: true,
                    message: result.message + '，请重新登录'
                }
            } else {
                error.value = result.message || '修改密码失败'
                console.log('❌ 修改失败:', error.value)
                return {
                    success: false,
                    message: error.value
                }
            }
        } catch (err) {
            console.error('💥 修改密码异常:', err)
            error.value = '网络错误，请稍后重试'
            return {
                success: false,
                message: error.value
            }
        } finally {
            isLoading.value = false
        }
    }

    // 登出
    const logout = () => {
        console.log('🚪 执行登出（清理所有状态）')
        user.value = null
        error.value = null
        userAPI.logout()
        console.log('✅ 登出完成（内存+本地存储已清空）')
    }

    // 登录状态判断
    const isLoggedIn = () => {
        const status = userAPI.isLoggedIn()
        console.log('🔐 登录状态校验:', { status, currentUser: user.value })
        return status
    }

    // 管理员判断
    const isAdmin = () => {
        const status = userAPI.hasRole('ROLE_ADMIN')
        console.log('👑 管理员权限校验:', { status, currentUser: user.value })
        return status
    }

    const clearError = () => {
        error.value = null
    }

    // 初始化认证状态
    initializeAuth()

    return {
        user,
        isLoading,
        error,
        login,
        register,
        logout,
        changePassword,
        deleteUser,
        refreshUserFromBackend,
        clearError,
        isLoggedIn,
        isAdmin
    }
})